const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const jwt = require('jsonwebtoken')
const { userLogin } = require('../model/login');
const { userRegister } = require('../model/register');

const mykey = 'fdskjfoiernknziure8';

let confrimText = '';

router.prefix('/users');

router.get('/getConfirm', async(ctx,next) => {
    const confirmImg = svgCaptcha.create();
    confrimText = confirmImg.text;
    ctx.body = {'code':200,'data':confirmImg.data}
})

router.post('/login', async (ctx, next) => {
    const email = ctx.request.body.email;
    const password = ctx.request.body.password;
    const confirm = ctx.request.body.confirm;
    const last_login_time = ctx.request.body.last_login_time;

    if(confirm !== confrimText) {
        return ctx.body = {'code':500,'msg':'验证码错误！'}
    }

    let res = await userLogin(email,password,last_login_time);

    if(res.msg === 'false1') {
        return ctx.body = {'code':500,'msg':'账号不存在！'}
    }

    if(res.msg === 'false2') {
        return ctx.body = {'code':500,'msg':'密码错误！'}
    }

    if(res.msg === 'true') {
        let token = jwt.sign({'email':email,'password':password},mykey)
        return ctx.body = {'code':200,'msg':'登录成功！',token,'userid':res.data.userid,'username':res.data.username,'email':res.data.email};
    }
})

router.post('/userRegister', async(ctx,next) => {
    const username = ctx.request.body.username;
    const password = ctx.request.body.password;
    const email = ctx.request.body.email;
    const create_time = ctx.request.body.create_time;

    let res = await userRegister(username,password,email,create_time);

    if(res === true) {
        ctx.body = {'code':200,'msg':'注册成功！'};
    }else if(res === 'false1') {
        ctx.body = {'code':500,'msg':'该邮箱已被注册！'};
    }else{
        ctx.body = {'code':500,'msg':'注册失败！'};
    }
})

module.exports = router
